#include "log.hpp"
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <cstring>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <memory>

class client
{
public:
    client(const string &serverIp, const uint16_t &serverPort)
        : _serverIp(serverIp), _serverPort(serverPort), _isrunning(false)
    {
        init();
    }
    ~client()
    {
        close(_fd);
    }
    void init()
    {
        _fd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_fd == -1)
        {
            log(ERROR, "open socket fail!");
            cout << "error: " << strerror(errno) << endl;
            exit(-1);
        }
        log(NOTICE, "open socket success!");
    }
    void run()
    {
        _isrunning = true;
        struct sockaddr_in server;
        server.sin_family = AF_INET;
        server.sin_addr.s_addr = inet_addr(_serverIp.c_str());
        server.sin_port = htons(_serverPort);

        cout<<"debug: "<<_serverIp.c_str()<<" "<<_serverPort<<endl;

        socklen_t len = sizeof(server);
        while (_isrunning)
        {
            string str;
            getline(cin, str);

            int n=sendto(_fd, str.c_str(), str.size(), 0,(const sockaddr *)&server,len);
            if(n==-1)
            {
                log(WARNING, "sendto fail!");
            }
            char buffer[1024];
            struct sockaddr_in temp;
            socklen_t len = sizeof(temp);
            n = recvfrom(_fd, buffer, sizeof(buffer) - 1, 0, (sockaddr *)&temp, &len);
            buffer[n] = '\0';
            cout << buffer << endl;
        }
    }

private:
    int _fd;
    string _serverIp;
    uint16_t _serverPort;
    bool _isrunning;
};
